package org.mspring.mlog.freemarker.directive;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.mspring.nbee.web.freemarker.DirectiveUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author Gao Youbo
 * @since 2015-01-04 18:18
 */
@Component
public class ArticleSummaryDirectiveModel implements TemplateDirectiveModel {
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String content = DirectiveUtils.getString("content", params);
        if (content == null) {
            return;
        }
        content = getHtmlContent(content);
        env.getOut().append(content);
    }


    public static String getHtmlContent(String content) {
        Document doc = Jsoup.parse(content);
        content = doc.text();
        if (StringUtils.length(content) > 350) {
            content = StringUtils.left(content, 350) + "...";
        }
        return content;
    }
}
